import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:openim_common/openim_common.dart';
import '../../../models/circle_models.dart';
import 'package:flutter_openim_sdk/flutter_openim_sdk.dart';

class PostSearchLogic extends GetxController {
  final searchCtrl = TextEditingController();
  final focusNode = FocusNode();

  final isSearching = false.obs;
  final hasSearched = false.obs;
  final results = <CirclePost>[].obs;

  String? circleId;

  @override
  void onInit() {
    final args = Get.arguments as Map<String, dynamic>?;
    circleId = args?['circleId'] as String?;
    super.onInit();
  }

  @override
  void onClose() {
    searchCtrl.dispose();
    focusNode.dispose();
    super.onClose();
  }

  void clearSearch() {
    searchCtrl.clear();
    results.clear();
    hasSearched.value = false;
  }

  Future<void> performSearch() async {
    final kw = searchCtrl.text.trim();
    if (kw.isEmpty) {
      clearSearch();
      return;
    }
    isSearching.value = true;
    hasSearched.value = true;

    try {
      final response = await Apis.searchPosts(
        keyword: kw,
        page: 1,
        pageSize: 20,
        circleId: circleId,
      );

      final postsData = response['posts'] as List?;
      if (postsData == null) {
        results.clear();
        IMViews.showToast('搜索失败：返回数据为空');
        return;
      }

      if (postsData.isEmpty) {
        results.clear();
        IMViews.showToast('没有找到与“$kw”相关的帖子');
        return;
      }

      // 收集 OpenIM 用户ID
      final Set<String> openimUserIds = {};
      for (var postJson in postsData) {
        final openimUserId = postJson['user']?['openim_user_id'];
        if (openimUserId != null && openimUserId.isNotEmpty) {
          openimUserIds.add(openimUserId);
        }
      }

      // 批量获取 OpenIM 用户信息（缓存 + 在线兜底）
      Map<String, dynamic> openimUserInfoMap = {};
      if (openimUserIds.isNotEmpty) {
        try {
          // 先尝试缓存
          final cachedList = await OpenIM.iMManager.userManager
              .getUsersInfoWithCache(openimUserIds.toList());
          final Set<String> missingIds = {};
          for (final userInfo in cachedList) {
            final id = userInfo.userID;
            if (id != null) {
              final nickname = userInfo.nickname;
              final faceURL = userInfo.faceURL;
              openimUserInfoMap[id] = {
                'nickname': nickname,
                'faceURL': faceURL,
              };
              if ((nickname == null || nickname.isEmpty) ||
                  (faceURL == null || faceURL.isEmpty)) {
                missingIds.add(id);
              }
            }
          }
          // 加入缓存未命中的ID
          for (final id in openimUserIds) {
            if (!openimUserInfoMap.containsKey(id)) {
              missingIds.add(id);
            }
          }
          // 在线补拉
          if (missingIds.isNotEmpty) {
            final onlineList = await OpenIM.iMManager.userManager
                .getUsersInfo(userIDList: missingIds.toList());
            for (final userInfo in onlineList) {
              final id = userInfo.userID;
              if (id != null) {
                final nickname =
                    userInfo.nickname ?? userInfo.simpleUserInfo?.nickname;
                final faceURL =
                    userInfo.faceURL ?? userInfo.simpleUserInfo?.faceURL;
                final existing = openimUserInfoMap[id];
                openimUserInfoMap[id] = {
                  'nickname': (nickname != null && nickname.isNotEmpty)
                      ? nickname
                      : (existing?['nickname']),
                  'faceURL': (faceURL != null && faceURL.isNotEmpty)
                      ? faceURL
                      : (existing?['faceURL']),
                };
              }
            }
          }
        } catch (e) {
          debugPrint('批量获取OpenIM用户信息失败: $e');
        }
      }

      // 构建 CirclePost 列表
      final List<CirclePost> mapped = [];
      for (var postJson in postsData) {
        final openimUserId = postJson['user']?['openim_user_id'];
        String userName = postJson['user']?['nickname'] ?? '未知用户';
        String userAvatar = postJson['user']?['avatar'] ?? '';
        if (openimUserId != null && openimUserInfoMap.containsKey(openimUserId)) {
          final openimInfo = openimUserInfoMap[openimUserId];
          userName = openimInfo['nickname'] ?? userName;
          userAvatar = openimInfo['faceURL'] ?? userAvatar;
        }

        final post = CirclePost(
          id: postJson['id'].toString(),
          userId: postJson['user_id'] ?? '',
          userName: userName,
          userAvatar: userAvatar,
          content: postJson['content'] ?? '',
          images: List<String>.from(postJson['images'] ?? []),
          videos: List<String>.from(postJson['videos'] ?? []),
          tags: parseTags(postJson['tags']),
          createdAt: DateTime.tryParse(postJson['created_at'] ?? '') ?? DateTime.now(),
          likeCount: postJson['like_count'] ?? 0,
          isLiked: postJson['is_liked'] ?? false,
          isBookmarked: postJson['is_collected'] ?? false,
          commentCount: postJson['comment_count'] ?? 0,
          shareCount: postJson['share_count'] ?? 0,
          circleId: postJson['circle_id'],
          circleName: postJson['circle']?['name'],
          circleType: _mapCircleTypeFromString(
            postJson['circle']?['type']?.toString() ?? 'city',
          ),
          locationLatitude: (() {
            final v = postJson['location_latitude'];
            if (v is num) return v.toDouble();
            if (v is String) return double.tryParse(v);
            return null;
          })(),
          locationLongitude: (() {
            final v = postJson['location_longitude'];
            if (v is num) return v.toDouble();
            if (v is String) return double.tryParse(v);
            return null;
          })(),
          locationAddress: postJson['location_address'],
        );
        mapped.add(post);
      }

      // 更新结果
      results
        ..clear()
        ..addAll(mapped);
    } catch (e) {
      IMViews.showToast('搜索失败: $e');
    } finally {
      isSearching.value = false;
    }
  }

  List<PostTag> parseTags(dynamic tagsJson) {
    if (tagsJson == null) return [];
    try {
      if (tagsJson is List) {
        return tagsJson
            .map((tagJson) => PostTag.fromJson(tagJson as Map<String, dynamic>))
            .toList();
      }
    } catch (e) {
      debugPrint('解析标签数据失败: $e');
    }
    return [];
  }

  CircleType _mapCircleTypeFromString(String typeString) {
    switch (typeString) {
      case 'city':
        return CircleType.city;
      case 'country':
        return CircleType.country;
      case 'global':
        return CircleType.global;
      default:
        return CircleType.city;
    }
  }
}